package com.ht.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.api.utils.StringUtils;
import com.ht.data.Result;
import com.ht.em.ResultEnum;
import com.ht.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Value("#{'${gateway.excludes.urls}'.empty ? null : '${gateway.excludes.urls}'.split(',')}")
    private Set<String> gatgatewayExcludesUrl;

    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求头 获取request对象
        ServerHttpRequest request = exchange.getRequest();

        //TODO 当前的请求路径
        String path = request.getURI().getPath();
        for (String excludeUrl : gatgatewayExcludesUrl) {
            if (pathMatcher.match(excludeUrl,path)){
                return chain.filter(exchange);
            }
        }

        //通过request对象获取请求头数据
        String token = request.getHeaders().getFirst("AuthToken");
        //检查token是否存在
        if (StringUtils.isBlank(token)){
            return response(exchange);
        }
        try{
            //token不对或者超时 或者 解析失败都会抛出异常 如果能解析出来 token就是正确的
            Claims claims = new JwtUtil().parseJwt(token);
        }catch (Exception e){
            return response(exchange);
        }
        // token 不为null 并且是正确的
        // 由于被调用的服务有可能会用到请求头 所有还要将请求头返回将token继续向下传递
        //防止请求头丢失
        //headers()参数是消费型接口
        // 保留 : 如果请求头丢失 我们就通过这种方式传递
//        request.mutate().headers(x->x.add("AuthToken",token)).build();
        //通过过滤器链 继续向下传递
        return chain.filter(exchange);
    }

    /**
     * 封装统一返回值
     * @param exchange
     * @return
     */
    public Mono<Void> response(ServerWebExchange exchange){
        //获取response对象 有了这个对象我们就可以返回数据了
        ServerHttpResponse response = exchange.getResponse();
        //设置响应状态  ok是这个请求成功
        response.setStatusCode(HttpStatus.OK);
        //设置返回头编码 否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //二进制的方式将结果输出的前台
        byte[] bytes = JSONObject.toJSONBytes(Result.response(ResultEnum.NO_LOGIN), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 过滤器执行的顺序 数值越小 越先执行 可以是负数
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
